<script setup lang='ts'>
  import { nextTick, reactive, ref } from 'vue';
  import { ChallengeApi, propApi } from '@/api/controller';
  import { ToastSuccess, ToastWarning, Toastloading, allNumber } from '@/utils/public';
import { ElMessageBox } from 'element-plus';
  const formLabelWidth = '130px'
  const dataForm = ref()
  const $emit = defineEmits(['updateList'])
  const action = reactive({
    dialogFormVisible:false,
    disabled:false,
    SessionList:[] as Array<any>,
    offer_reward:[] as Array<any>,
    poolList:[] as Array<any>,
    giftList:[] as Array<any>,
    gift_id:''
  })
  interface formQuert {
    id:number
    game_id:number
    second:number
    rate:number
    offer_draw:number
    offer_reward:Array<any>,
  }
  let form = reactive({} as formQuert)
  let listQuery = reactive({
    game_id:''
  })
  const formRules = {
    giftNum:[
      { required: true, message: '请填写悬赏礼物数量', trigger: 'change' }
    ],
    rate: [
      { required: true, message: '请输入概率', trigger: 'change' }
    ],
    offer_draw: [
      { required: true, message: '请选择悬赏人物', trigger: 'change' }
    ],
    second: [
      { required: true, message: '请输入悬赏毫秒数', trigger: 'change' }
    ],
  }
  const changeGameID = async()=>{
    Object.assign(form,{
      game_id:form.game_id,
      rate:null,
      offer_draw:[],
      second:null
    })
    action.offer_reward = []
    action.gift_id = ''
    const timeOut = setTimeout(() => {
      dataForm.value.clearValidate();
      clearTimeout(timeOut)
    }, 0);
    await getpoolList()
  }
  const handleSubmit = ()=>{
    let key = action.offer_reward.findIndex(res=> {
      if(res.num <= 0 || res.jd_num <=0) return
    } )
    if(key >= 0) return ToastWarning('请填写完整的悬赏奖励信息')
    dataForm.value.validate(async(valid:any)=>{
      if(!valid) return
      const loading = Toastloading()
      const { id=0, } = form
      const formQuery = JSON.parse(JSON.stringify(form))
      formQuery.offer_reward = JSON.stringify(action.offer_reward)
      formQuery.offer_draw = JSON.stringify(formQuery.offer_draw)
      let submitSet = false
      if(id) {
        await ChallengeApi.offerEdit({
          id,
          ...formQuery
        }).then(res=>{
          submitSet = true
          ToastSuccess('修改成功')
        }).catch(()=>{
          loading.close()
        })
      }else {
        await ChallengeApi.offerAdd(formQuery).then(()=>{
          submitSet = true
          ToastSuccess('新增成功')
        }).catch(()=>{
          loading.close()
        })
      }
      if(submitSet) {
        loading.close()
        closeDialog()
        $emit('updateList')
      }
    })
  }
  const openDialog = async(query:any = {})=> {
    const {
      id=0,
      game_id=null,
      rate=null,
      offer_draw=[],
      offer_reward=[],
      second=null,
      SessionList=[]
    } = query
    if(!Array.isArray(offer_draw)) return ToastWarning('offer_draw Not of this Array')
    if(!Array.isArray(offer_reward)) return ToastWarning('offer_reward Not of this Array')
    const formQuery = {
      game_id,
      rate,
      offer_draw:offer_draw.map(res=>res.item_id),
      second
    } as any
    action.offer_reward = JSON.parse(JSON.stringify(offer_reward))

    if(id) formQuery['id'] = id
    Object.assign(form,{
      ...formQuery
    })
    const loading = Toastloading()
    action.SessionList = SessionList
    await getGiftsList()
    await getpoolList()
    loading.close()
    action.dialogFormVisible = true
  }
  const getGiftsList = async()=>{
    await propApi.getGifts({limit:1000}).then((res) => {
      const { data=[] } = res.data
      action.giftList = data
    })
  }
  const getpoolList = async()=>{
    action.poolList = []
    await ChallengeApi.poolList({
      game_id:form.game_id
    }).then((res) => {
      const { data=[] } = res
      action.poolList = data.filter((res:any)=> res.item_type == 1)
    })
  }
  const addGift = ()=>{
    if(!action.gift_id) return ToastWarning('请选择悬赏奖励')
    const index = action.offer_reward.findIndex(res=>res.gift_id == action.gift_id)
    if(index > -1) return ToastWarning('当前悬赏奖励已存在')
    const giftObj = action.giftList.find(res=>res.gift_id == action.gift_id) || { name:'' }
    action.offer_reward.push({
      gift_id:action.gift_id,
      gift_name:giftObj.name,
      num:0
    })
    action.gift_id = ''
  }
  const delGift = (row:any={})=>{
    const { gift_id=0, gift_name='' } = row
    if(!gift_id) ToastWarning('缺少gift_id')
    ElMessageBox.confirm(`确认删除悬赏奖励：${gift_name}吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      const index = action.offer_reward.findIndex(res=>res.gift_id == gift_id)
      if(index == -1) return ToastWarning('奖励下标获取异常')
      action.offer_reward.splice(index,1)
      ToastSuccess("删除成功!");
    }).catch(() => {});
  }
  const closeDialog = ()=>{
    form = reactive({} as formQuert)
    nextTick(() => {
      dataForm.value.clearValidate();
    });
    action.dialogFormVisible = false
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
    top="5vh"
    class="xm-dialog input-width xm-dialog-cont-y "
    v-model="action.dialogFormVisible"
    :close-on-click-modal="action.disabled"
    :show-close="action.disabled"
    :close-on-press-escape="action.disabled"
    width="55%"
    :title="`${form.id?'修改':'新增'}悬赏奖励配置`">
      <el-form ref="dataForm" :model="form" :rules="formRules">
        <el-row>
          <el-col :span="12">
            <template v-if="!form.id">
              <el-form-item :label-width="formLabelWidth" label="游戏类型：">
                <el-select @change="changeGameID" v-model="form.game_id" placeholder="请选择">
                  <el-option
                    v-for="item in action.SessionList"
                    :key="item.game_id"
                    :label="item.game_name"
                    :value="item.game_id">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
            <el-form-item :label-width="formLabelWidth" label="悬赏时间" prop="second" @input="allNumber(form,'second')" >
              <el-input v-model="form.second" placeholder="请以秒为时间单位填写" />
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="概率" prop="rate" @input="allNumber(form,'rate')">
              <el-input v-model="form.rate" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label-width="formLabelWidth" label="悬赏人物" prop="offer_draw">
              <el-select 
                multiple
                filterable
                v-model="form.offer_draw" placeholder="请选择">
                <el-option
                  v-for="item in action.poolList"
                  :key="item.id"
                  :label="item.item_name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="xm-headTab">
        <div class="labelBox">
          <div class="labelItem">
            <div class="label">悬赏奖励：</div>
            <el-select filterable v-model="action.gift_id" placeholder="请选择">
              <el-option
                v-for="item in action.giftList"
                :key="item.gift_id"
                :label="item.name"
                :value="item.gift_id" />
              </el-select>
            </div>
          <div class="labelItem">
            <el-button type="primary" @click="addGift">添加悬赏奖励</el-button>
          </div>
        </div>
      </div>
      <el-table
        class="xm-main xm-TableCenter"
        :data="action.offer_reward"
        border>
        <el-table-column min-width="100" prop="gift_name" label="礼物名称" />
        <el-table-column min-width="100" label="礼物数量">
          <template #default="scope">
            <el-input
              style="width: 100%;"
              v-model="scope.row.num"
              @input="allNumber(scope.row,'num')"
              placeholder="请填写礼物数量" />
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="奖励金豆数">
          <template #default="scope">
              <el-input
              style="width: 100%;"
              v-model="scope.row.jd_num"
              @input="allNumber(scope.row,'num')"
              placeholder="请填写奖励金豆数" />
          </template>
        </el-table-column>
        <el-table-column width="120" fixed=right label="操作">
          <template #default="scope">
            <el-button type="danger" @click="delGift(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template v-if="!action.disabled" #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>